#include "widget.h"
#include "ui_widget.h"

#include <QFileDialog>
#include <QMessageBox>
#include <QShortcut>
#include <QDebug>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setLayout(ui->verticalLayout);
    ui->label->setText("行: ,列: ");

    QShortcut *shortcutOpen = new QShortcut(QKeySequence(tr("Ctrl+O", "File|Open")), this);
    QShortcut *shortcutSave = new QShortcut(QKeySequence(tr("Ctrl+S", "File|Save")), this);

    QShortcut *shortcutZoomIn = new QShortcut(QKeySequence(tr("Ctrl+Shift+=", "File|Save")), this);
    QShortcut *shortcutZoomOut = new QShortcut(QKeySequence(tr("Ctrl+Shift+-", "File|Save")), this);

    connect(shortcutOpen, &QShortcut::activated, [=]{
        on_btnOpen_clicked();
    });

    connect(shortcutSave, &QShortcut::activated, [=]{
        on_btnSave_clicked();
    });

    connect(shortcutZoomIn, &QShortcut::activated, [=]{
        zoomIn();
    });

    connect(shortcutZoomOut, &QShortcut::activated, [=]{
        zoomOut();
    });

    connect(ui->comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(onCurrentIndexChanged(int )));
    connect(ui->textEdit, SIGNAL(cursorPositionChanged()), this, SLOT(onCursorPositionChanged()));
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_btnOpen_clicked()
{
    //1.设置对话框的模式 2.输入文件路劲 3.设置过滤器
    QString filename =  QFileDialog::getOpenFileName(this,tr("Open File"),
    "D:/qt_project/bigProject/", tr("Text (*.txt)"));


    ui->textEdit->clear();//清空所有文字

    file.setFileName(filename);
    if(!file.open(QIODevice::ReadWrite | QIODevice::Text)){
        qDebug() << "file open error";
    }

    this->setWindowTitle(filename + "- 曙哥记事本");

    QTextStream in(&file);
    //in.setEncoding(QStringConverter::Utf8);
    QString encodingStr = ui->comboBox->currentText();
    if (encodingStr == "UTF-8") {
        in.setEncoding(QStringConverter::Utf8);
    } else if (encodingStr == "UTF-16") {
        in.setEncoding(QStringConverter::Utf16);
    } else {
        in.setEncoding(QStringConverter::System); // 默认系统编码
    }

    // QStringConverter::Encoding encoding = ui->comboBox->currentData().value<QStringConverter::Encoding>();
    // in.setEncoding(encoding);

    // QString context = in.read(file.size());
    while(!in.atEnd()){
        QString context = in.readLine();
        //ui->textEdit->setText(context);
        ui->textEdit->append(context);//    把每一行追加到记事本里
    }

}


void Widget::on_btnSave_clicked()
{
    if(!file.isOpen()){
        QString filename =  QFileDialog::getSaveFileName(this,tr("Save File"),
        "D:/qt_project/bigProject/untitled.txt", tr("Text (*.doc *.txt)"));

        this->setWindowTitle(filename + "- 曙哥记事本");

        file.setFileName(filename);
        if(!file.open(QIODevice::WriteOnly | QIODevice::Text)){ //文件打开模式为只读和文本模式
            qDebug() << "file open error";
        }
    }


    QTextStream out(&file);
    QString encodingStr = ui->comboBox->currentText();
    if (encodingStr == "UTF-8") {
        out.setEncoding(QStringConverter::Utf8);
    } else if (encodingStr == "UTF-16") {
        out.setEncoding(QStringConverter::Utf16);
    } else {
        out.setEncoding(QStringConverter::System); // 默认系统编码
    }
    QString context = ui->textEdit->toPlainText();
    out << context;
}





void Widget::on_btnClose_clicked()
{

    QMessageBox msgBox;

    int ret = QMessageBox::warning(this, tr("曙哥记事本"),
                                   tr("文档已修改.\n"
                                      "要保存更改吗?"),
                                   QMessageBox::Save | QMessageBox::Discard
                                       | QMessageBox::Cancel,
                                   QMessageBox::Save);

    switch (ret) {
    case QMessageBox::Save:
        // Save was clicked
        on_btnSave_clicked();
        break;
    case QMessageBox::Discard:
        // Don't Save was clicked
        ui->textEdit->clear();
        if(file.isOpen()){
            file.close();
            this->setWindowTitle("曙哥记事本");
        }

        qDebug() << "Discard";
        break;
    case QMessageBox::Cancel:
        // Cancel was clicked
        qDebug() << "Cancel";
        break;
    default:
        // should never be reached
        break;
    }

}

void Widget::onCurrentIndexChanged(int )
{
    ui->textEdit->clear();
    if(file.isOpen()){
        QTextStream in(&file);
        QString encodingStr = ui->comboBox->currentText();
        if (encodingStr == "UTF-8") {
            in.setEncoding(QStringConverter::Utf8);
        } else if (encodingStr == "UTF-16") {
            in.setEncoding(QStringConverter::Utf16);
        } else {
            in.setEncoding(QStringConverter::System); // 默认系统编码
        }
        file.seek(0);//光标回到最出位置
        while(!in.atEnd()){
            QString context = in.readLine();
            ui->textEdit->append(context);
        }
    }
}

void Widget::onCursorPositionChanged()
{
    QTextCursor cursor = ui->textEdit->textCursor();
    //qDebug() << cursor.blockNumber() + 1 << "," << cursor.columnNumber() + 1;
    QString blockNum = QString::number(cursor.blockNumber() + 1);
    QString columNum = QString::number(cursor.columnNumber() + 1);
    const QString labelMes = "行:" + blockNum + ",列:" + columNum + "  ";
    ui->label->setText(labelMes);

    //设置当前行高亮
    QList<QTextEdit::ExtraSelection> extraSelection;
    QTextEdit::ExtraSelection ext;

    //1.知道当前行
    ext.cursor = cursor;
    QBrush qBrush(Qt::lightGray);
    //2.颜色
    ext.format.setBackground(qBrush);
    //整行显示
    ext.format.setProperty(QTextFormat::FullWidthSelection, true);
    //3.设置
    extraSelection.append(ext);
    ui->textEdit->setExtraSelections(extraSelection);

}

void Widget::zoomIn()
{
    QFont font = ui->textEdit->font();

    //获得当前字体的大小
    int fontsize = font.pointSize();
    if(fontsize == -1) return;
    int newFontSize = fontsize + 1;
    font.setPointSize(newFontSize);
    ui->textEdit->setFont(font);
}

void Widget::zoomOut()
{
    //获得当前字体的信息
    QFont font = ui->textEdit->font();

    //获得当前字体的大小
    int fontsize = font.pointSize();
    if(fontsize == -1) return;
    int newFontSize = fontsize - 1;
    font.setPointSize(newFontSize);
    ui->textEdit->setFont(font);
}

